<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,学习笔记,量化投资,Backtrader," />










<meta name="description" content="上次利用Backtrader对实盘交易记录进行了回测。现在打算对程序进行重构，参考《重构——改善既有代码的设计》。先用git branch refactoring开一个分支，checkout到该分支开始干活。先是一些基本理论。如果发现由于代码结构无法方便的为程序添加特性，就先重构程序，使特性添加比较容易，再添加特性。重构的第一步:建立可靠的测试环境。重构步骤的本质:由于每次修改的幅度都很小，所以任">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记77——重构回测程序">
<meta property="og:url" content="https://zwdnet.github.io/2020/07/17/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B077%E2%80%94%E2%80%94%E9%87%8D%E6%9E%84%E5%9B%9E%E6%B5%8B%E7%A8%8B%E5%BA%8F/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="上次利用Backtrader对实盘交易记录进行了回测。现在打算对程序进行重构，参考《重构——改善既有代码的设计》。先用git branch refactoring开一个分支，checkout到该分支开始干活。先是一些基本理论。如果发现由于代码结构无法方便的为程序添加特性，就先重构程序，使特性添加比较容易，再添加特性。重构的第一步:建立可靠的测试环境。重构步骤的本质:由于每次修改的幅度都很小，所以任">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-07-17T04:42:34.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="Backtrader">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/07/17/量化投资学习笔记77——重构回测程序/"/>





  <title>量化投资学习笔记77——重构回测程序 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/07/17/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B077%E2%80%94%E2%80%94%E9%87%8D%E6%9E%84%E5%9B%9E%E6%B5%8B%E7%A8%8B%E5%BA%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记77——重构回测程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-17T04:42:34+00:00">
                2020-07-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  16
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>上次利用Backtrader对实盘交易记录进行了回测。现在打算对程序进行重构，参考《重构——改善既有代码的设计》。<br>先用git branch refactoring开一个分支，checkout到该分支开始干活。<br>先是一些基本理论。<br>如果发现由于代码结构无法方便的为程序添加特性，就先重构程序，使特性添加比较容易，再添加特性。<br>重构的第一步:建立可靠的测试环境。<br>重构步骤的本质:由于每次修改的幅度都很小，所以任何错误都很容易发现。<br>任何一个傻瓜都能写出计算机可以理解的代码。惟有写出人类容易理解的代码，才是优秀的程序员。<br>重构是在不改变软件可见行为的前提下，提高其可读性，降低修改成本。<br>增添功能与重构分开。<br>重构改进软件设计，使软件更容易被理解，帮助调试，提高编程速度。<br>何时重构?事不过三，三则重构。添加功能，修补错误，代码复审时重构。<br>下面就来看看我上次写的代码有什么”坏味道”</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># 用backtrader对定投实盘记录进行回测</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> backtrader <span class="keyword">as</span> bt</span><br><span class="line"><span class="keyword">import</span> backtrader.analyzers <span class="keyword">as</span> btay</span><br><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getData</span>(<span class="params">code, start, end</span>):</span></span><br><span class="line">    filename = code+<span class="string">&quot;.csv&quot;</span></span><br><span class="line">    print(<span class="string">&quot;./&quot;</span> + filename)</span><br><span class="line">    <span class="comment"># 已有数据文件，直接读取数据</span></span><br><span class="line">    <span class="keyword">if</span> os.path.exists(<span class="string">&quot;./&quot;</span> + filename):</span><br><span class="line">        df = pd.read_csv(filename)</span><br><span class="line">    <span class="keyword">else</span>: <span class="comment"># 没有数据文件，用tushare下载</span></span><br><span class="line">        df = ts.get_k_data(code, autype = <span class="string">&quot;qfq&quot;</span>, start = start,  end = end)</span><br><span class="line">        df.to_csv(filename)</span><br><span class="line">    df.index = pd.to_datetime(df.date)</span><br><span class="line">    df[<span class="string">&#x27;openinterest&#x27;</span>]=<span class="number">0</span></span><br><span class="line">    df=df[[<span class="string">&#x27;open&#x27;</span>,<span class="string">&#x27;high&#x27;</span>,<span class="string">&#x27;low&#x27;</span>,<span class="string">&#x27;close&#x27;</span>,<span class="string">&#x27;volume&#x27;</span>,<span class="string">&#x27;openinterest&#x27;</span>]]</span><br><span class="line">    <span class="keyword">return</span> df</span><br><span class="line">   </span><br><span class="line">   </span><br><span class="line"><span class="comment"># 交易策略</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TradeStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    params = (</span><br><span class="line">            (<span class="string">&quot;recordFilename&quot;</span>, <span class="string">&quot;etfdata.csv&quot;</span>),</span><br><span class="line">            (<span class="string">&quot;printlog&quot;</span>, <span class="literal">False</span>)</span><br><span class="line">    )</span><br><span class="line">   </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.df_record = pd.read_csv(self.params.recordFilename)</span><br><span class="line">        self.df_record.成交日期 = pd.to_datetime(self.df_record.成交日期, <span class="built_in">format</span> = <span class="string">&quot;%Y%m%d&quot;</span>)</span><br><span class="line">        self.df_record.index = self.df_record.成交日期</span><br><span class="line">        self.df_record.drop(labels = <span class="string">&quot;成交日期&quot;</span>, axis = <span class="number">1</span>, inplace = <span class="literal">True</span>)</span><br><span class="line">        <span class="comment"># print(self.df_record.head(), self.df_record.info())</span></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">        ad = bt.indicators.AroonDown(plotname = <span class="string">&quot;AD&quot;</span>)</span><br><span class="line">        ad.plotinfo.subplot = <span class="literal">True</span></span><br><span class="line">       </span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt, dt=<span class="literal">None</span>, doprint=<span class="literal">False</span></span>):</span></span><br><span class="line">        <span class="string">&#x27;&#x27;&#x27;log记录&#x27;&#x27;&#x27;</span></span><br><span class="line">        <span class="keyword">if</span> self.params.printlog <span class="keyword">or</span> doprint:</span><br><span class="line">            dt = dt <span class="keyword">or</span> self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">            print(<span class="string">&#x27;%s, %s&#x27;</span> % (dt.isoformat(), txt))</span><br><span class="line">           </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">        <span class="comment"># 有交易提交/被接受，啥也不做</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">        <span class="comment"># 检查一个交易是否完成。</span></span><br><span class="line">        <span class="comment"># 如果钱不够，交易会被拒绝。</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">            <span class="keyword">if</span> order.isbuy():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行买入, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line">                <span class="comment"># self.buyprice = order.executed.price</span></span><br><span class="line">                <span class="comment"># self.buycomm = order.executed.comm</span></span><br><span class="line">            <span class="keyword">elif</span> order.issell():</span><br><span class="line">                self.log(</span><br><span class="line">                    <span class="string">&#x27;执行卖出, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line"></span><br><span class="line">            self.bar_executed = <span class="built_in">len</span>(self)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">elif</span> order.status <span class="keyword">in</span> [order.Canceled, order.Margin, order.Rejected]:</span><br><span class="line">            self.log(<span class="string">&#x27;交易取消/被拒绝。&#x27;</span>)</span><br><span class="line"></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">if</span> self.order:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        tradeData = pd.DataFrame()</span><br><span class="line">        orderType = bt.Order.Market</span><br><span class="line">        <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">            date = data.datetime.date(<span class="number">0</span>)</span><br><span class="line">            tradeBar = self.df_record.loc[date.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>),:]</span><br><span class="line">            <span class="comment"># print(&quot;bar数据&quot;, date, data._name)</span></span><br><span class="line">            <span class="keyword">if</span> <span class="built_in">len</span>(tradeBar) != <span class="number">0</span>:</span><br><span class="line">                <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tradeBar)):</span><br><span class="line">                    name = tradeBar.iloc[i].证券名称</span><br><span class="line">                    price = tradeBar.iloc[i].成交均价</span><br><span class="line">                    stock = tradeBar.iloc[i].成交量</span><br><span class="line">                    commit = tradeBar.iloc[i].手续费</span><br><span class="line">                    <span class="comment"># 进行交易</span></span><br><span class="line">                    <span class="keyword">if</span> stock &gt; <span class="number">0</span> <span class="keyword">and</span> name == data._name:</span><br><span class="line">                        <span class="comment"># print(&quot;测试a&quot;, date, name, price, stock, commit)</span></span><br><span class="line">                        self.broker.add_cash(price*stock + commit)</span><br><span class="line">                        <span class="comment"># print(self.broker.get_cash())</span></span><br><span class="line">                        self.order = self.buy(data = data, size = stock, price = price, exectype = orderType)</span><br><span class="line">                    <span class="keyword">elif</span> stock &lt; <span class="number">0</span> <span class="keyword">and</span> name == data._name:</span><br><span class="line">                        <span class="comment"># print(&quot;测试b&quot;, date, name, price, stock, commit)</span></span><br><span class="line">                        self.order = self.sell(data = data, size = -<span class="number">1</span>*stock, price = price, exectype = orderType)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">stop</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.log(<span class="string">&quot;最大回撤:-%.2f%%&quot;</span> % self.stats.drawdown.maxdrawdown[-<span class="number">1</span>], doprint=<span class="literal">True</span>)</span><br><span class="line">                   </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    start = <span class="string">&quot;2018-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2020-07-05&quot;</span></span><br><span class="line">    df_300 = getData(<span class="string">&quot;510300&quot;</span>, start, end)</span><br><span class="line">    df_nas = getData(<span class="string">&quot;513100&quot;</span>, start, end)</span><br><span class="line">    <span class="comment"># print(df_300.info(), df_nas.info())</span></span><br><span class="line">    <span class="comment"># 建立数据源</span></span><br><span class="line">    start_date = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, start.split(<span class="string">&quot;-&quot;</span>)))</span><br><span class="line">    end_date = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, end.split(<span class="string">&quot;-&quot;</span>)))</span><br><span class="line">    data300 = bt.feeds.PandasData(dataname = df_300, name = <span class="string">&quot;300ETF&quot;</span>, fromdate = datetime.datetime(start_date[<span class="number">0</span>], start_date[<span class="number">1</span>], start_date[<span class="number">2</span>]), todate = datetime.datetime(end_date[<span class="number">0</span>], end_date[<span class="number">1</span>], end_date[<span class="number">2</span>]))</span><br><span class="line">    dataNas = bt.feeds.PandasData(dataname = df_nas, name = <span class="string">&quot;nasETF&quot;</span>, fromdate = datetime.datetime(start_date[<span class="number">0</span>], start_date[<span class="number">1</span>], start_date[<span class="number">2</span>]), todate = datetime.datetime(end_date[<span class="number">0</span>], end_date[<span class="number">1</span>], end_date[<span class="number">2</span>]))</span><br><span class="line">    <span class="comment"># 建立回测实例，加载数据，策略。</span></span><br><span class="line">    cerebro = bt.Cerebro()</span><br><span class="line">    cerebro.addstrategy(TradeStrategy)</span><br><span class="line">    cerebro.adddata(data300, name = <span class="string">&quot;300ETF&quot;</span>)</span><br><span class="line">    cerebro.adddata(dataNas, name = <span class="string">&quot;nasETF&quot;</span>)</span><br><span class="line">    <span class="comment"># 添加回撤观察器</span></span><br><span class="line">    cerebro.addobserver(bt.observers.DrawDown)</span><br><span class="line">    <span class="comment"># 设置手续费</span></span><br><span class="line">    cerebro.broker.setcommission(commission=<span class="number">0.0003</span>)</span><br><span class="line">    <span class="comment"># 设置初始资金为0.01</span></span><br><span class="line">    cerebro.broker.setcash(<span class="number">0.01</span>)</span><br><span class="line">    print(<span class="string">&quot;初始资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    <span class="comment"># 添加分析对象</span></span><br><span class="line">    cerebro.addanalyzer(btay.SharpeRatio, _name = <span class="string">&quot;sharpe&quot;</span>, riskfreerate = <span class="number">0.02</span>)</span><br><span class="line">    cerebro.addanalyzer(btay.AnnualReturn, _name = <span class="string">&quot;AR&quot;</span>)</span><br><span class="line">    cerebro.addanalyzer(btay.DrawDown, _name = <span class="string">&quot;DD&quot;</span>)</span><br><span class="line">    cerebro.addanalyzer(btay.Returns, _name = <span class="string">&quot;RE&quot;</span>)</span><br><span class="line">    cerebro.addanalyzer(btay.TradeAnalyzer, _name = <span class="string">&quot;TA&quot;</span>)</span><br><span class="line">    <span class="comment"># 运行回测</span></span><br><span class="line">    results = cerebro.run()</span><br><span class="line">    <span class="comment"># cerebro.broker.add_cash(-10000.0)</span></span><br><span class="line">    print(<span class="string">&quot;期末资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    cerebro.plot(numfigs = <span class="number">2</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;result.png&quot;</span>)</span><br><span class="line">    print(<span class="string">&quot;夏普比例:&quot;</span>, results[<span class="number">0</span>].analyzers.sharpe.get_analysis()[<span class="string">&quot;sharperatio&quot;</span>])</span><br><span class="line">    print(<span class="string">&quot;年化收益率:&quot;</span>, results[<span class="number">0</span>].analyzers.AR.get_analysis())</span><br><span class="line">    print(<span class="string">&quot;最大回撤:%.2f，最大回撤周期%d&quot;</span> % (results[<span class="number">0</span>].analyzers.DD.get_analysis().<span class="built_in">max</span>.drawdown, results[<span class="number">0</span>].analyzers.DD.get_analysis().<span class="built_in">max</span>.<span class="built_in">len</span>))</span><br><span class="line">    print(<span class="string">&quot;总收益率:%.2f&quot;</span> % (results[<span class="number">0</span>].analyzers.RE.get_analysis()[<span class="string">&quot;rtot&quot;</span>]))</span><br><span class="line">    results[<span class="number">0</span>].analyzers.TA.print()</span><br></pre></td></tr></table></figure>
<p>1.重复的代码<br>notify_order成员函数里，以及数据初始化里都有重复的代码。<br>2.过长函数<br>main函数，next成员函数都太长了。<br>每当感觉需要以注释来说明点什么的时候，我们就把需要说明的东西写进一个独立函数中，并以其用途（而非实现手法)命名。我们<br>可以对一组或甚至短短一行代码做这件事。哪怕替换后的函数调用动作比函数自身还长，只要函数名称能够解释其用途，我们也该毫不犹豫地那么做。<br>3.过大的类<br>单一类不要做太多事，python这个问题貌似不严重。<br>4.过长参数列表<br>面向对象，函数需要的某些参数可以设为类成员变量，而不必作为函数参数。问题是很多python库都有长参数列的问题。<br>5.发散式变化<br>针对某一变化需要修改多个类的情况，最好将类拆分为数个，使每个变化只需修改一个类。<br>策略类貌似还可以改。<br>6.散弹式修改<br>一个变化要修改多个类，可将这些类合并，使得每个变化只修改一个类。<br>7.依恋情结<br>成员函数对某个对象的兴趣高于对自己的类的兴趣。<br>8.数据泥团<br>几个类中有相同的数据项。<br>9.基本类型偏执<br>用基本类型组成一些类型。<br>10.switch问题<br>少用，考虑用多态替代。python貌似没有。<br>11.平行继承体系<br>为某个类增加之类时需要为另一个类也增加子类。<br>12.冗余类<br>没啥用的类，删!<br>13.为未来设计<br>函数和类的唯一用户是测试程序。<br>14.临时变量<br>仅为某种特定情况设置的临时变量。<br>15.过度耦合的消息链<br>一个对象要求另一个对象，另一个对象在要求别的对象……<br>16.中间人<br>一个类需要太多调用另一个类完成其功能。直接调用实际工作的类。<br>17.亲密关系<br>两个类关系密切。分开或合并。<br>18.异曲同工的类<br>做类似的工作却有不同名称的类。合并。<br>19.不完美的程序库<br>自己改吧。<br>20.纯数据类<br>将使用该类的地方移入类中。<br>21.被拒绝的遗赠<br>子类不想继承父类某些内容。设计错误，重新设计。<br>22.过多的注释<br>多余的注释，说明代码需要重构。<br>进行重构，首要前提是有一个可靠的测试环境。就是要先有测试再重构啦，搜了一下，python标准库自带了unittest，但不太好用。还有个pytest，试试这个。<br>花了几天看了一下pytest，会基本操作了。主要就是以test_开头或_test结尾命名测试函数或类，可以保存到以test_xxx为文件名的单独文件里，然后在命令行里用pytest执行测试。测试里主要用assert语句进行测试。其它用法参见文档吧。继续重构。本来想先为原来的程序写单元测试，但是原来的程序都搅和到一起了，很难测试。这也是我想要重构的原因。<br>提炼函数(extract method)<br>将长的函数提炼成几个短的函数，或者类。main函数部分太长了，分成几个部分吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    <span class="comment"># 加载数据，建立数据源</span></span><br><span class="line">    data300, dataNas = createDataFeeds()</span><br><span class="line">    cerebro = createBacktesting(data300, dataNas)</span><br><span class="line">    <span class="comment"># 运行回测</span></span><br><span class="line">    print(<span class="string">&quot;初始资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    results = cerebro.run()</span><br><span class="line">    print(<span class="string">&quot;期末资金:%.2f&quot;</span> % cerebro.broker.getvalue())</span><br><span class="line">    outputResult(cerebro)</span><br></pre></td></tr></table></figure>
<p>分成这么几个函数，主函数短多了。<br>TradeStrategy类里的next函数也太长了，把交易功能提成函数吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">__doTrade</span>(<span class="params">self, data, name, price, stock, commit, orderType</span>):</span></span><br><span class="line">    <span class="keyword">if</span> stock &gt; <span class="number">0</span> <span class="keyword">and</span> name == data._name:</span><br><span class="line">        self.broker.add_cash(price*stock + commit)</span><br><span class="line">        self.order = self.buy(data = data, size = stock, price = price, exectype = orderType)</span><br><span class="line">    <span class="keyword">elif</span> stock &lt; <span class="number">0</span> <span class="keyword">and</span> name == data._name:</span><br><span class="line">        self.order = self.sell(data = data, size = -<span class="number">1</span>*stock, price = price, exectype = orderType)</span><br><span class="line">       </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">    <span class="keyword">if</span> self.order:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    tradeData = pd.DataFrame()</span><br><span class="line">    orderType = bt.Order.Market</span><br><span class="line">    <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">        date = data.datetime.date(<span class="number">0</span>)</span><br><span class="line">        tradeBar = self.df_record.loc[date.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>),:]</span><br><span class="line">        <span class="comment"># print(&quot;bar数据&quot;, date, data._name)</span></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(tradeBar) != <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tradeBar)):</span><br><span class="line">                name = tradeBar.iloc[i].证券名称</span><br><span class="line">                price = tradeBar.iloc[i].成交均价</span><br><span class="line">                stock = tradeBar.iloc[i].成交量</span><br><span class="line">                commit = tradeBar.iloc[i].手续费</span><br><span class="line">                <span class="comment"># 进行交易</span></span><br><span class="line">                self.__doTrade(data, name, price, stock, commit, orderType)</span><br></pre></td></tr></table></figure>
<p>有几种情况:没有使用变量的，直接提出去即可。使用了变量但是没有改变的，只在提炼区里使用的，在提炼函数里声明使用;在提炼区外也使用的，作为参数传入。提炼区改变了并且提炼区外要使用的变量，提炼函数返回值返回。<br>再把交易过程从next()函数中完全提取出来吧</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 具体交易逻辑，可以改的。</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">doTrade</span>(<span class="params">self</span>):</span></span><br><span class="line">    tradeData = pd.DataFrame()</span><br><span class="line">    orderType = bt.Order.Market</span><br><span class="line">    <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">        date = data.datetime.date(<span class="number">0</span>)</span><br><span class="line">        tradeBar = self.df_record.loc[date.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>),:]</span><br><span class="line">        <span class="comment"># print(&quot;bar数据&quot;, date, data._name)</span></span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">len</span>(tradeBar) != <span class="number">0</span>:</span><br><span class="line">            <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(tradeBar)):</span><br><span class="line">                name = tradeBar.iloc[i].证券名称</span><br><span class="line">                price = tradeBar.iloc[i].成交均价</span><br><span class="line">                stock = tradeBar.iloc[i].成交量</span><br><span class="line">                commit = tradeBar.iloc[i].手续费</span><br><span class="line">                <span class="comment"># 进行交易</span></span><br><span class="line">                self.__doTrade(data, name, price, stock, commit, orderType)</span><br><span class="line">       </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">    <span class="keyword">if</span> self.order:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">    self.doTrade()</span><br></pre></td></tr></table></figure>
<p>再改策略的时候直接改doTrade就行了。<br>再改一下notify_order成员函数，把重复的地方提炼成函数。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 输出交易过程</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">__displayOrder</span>(<span class="params">self, buy, order</span>):</span></span><br><span class="line">    <span class="keyword">if</span> buy:</span><br><span class="line">        self.log(</span><br><span class="line">                <span class="string">&#x27;执行买入, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                (order.executed.price,</span><br><span class="line">                 order.executed.value,</span><br><span class="line">                 order.executed.comm))</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        self.log(</span><br><span class="line">                <span class="string">&#x27;执行卖出, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                (order.executed.price,</span><br><span class="line">                 order.executed.value,</span><br><span class="line">                 order.executed.comm))</span><br><span class="line">       </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">    <span class="comment"># 有交易提交/被接受，啥也不做</span></span><br><span class="line">    <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 检查一个交易是否完成。</span></span><br><span class="line">    <span class="comment"># 如果钱不够，交易会被拒绝。</span></span><br><span class="line">    <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">        <span class="keyword">if</span> order.isbuy():</span><br><span class="line">            self.__displayOrder(<span class="literal">True</span>, order)</span><br><span class="line">        <span class="keyword">elif</span> order.issell():</span><br><span class="line">            self.__displayOrder(<span class="literal">False</span>, order)</span><br><span class="line"></span><br><span class="line">        self.bar_executed = <span class="built_in">len</span>(self)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">elif</span> order.status <span class="keyword">in</span> [order.Canceled, order.Margin, order.Rejected]:</span><br><span class="line">        self.log(<span class="string">&#x27;交易取消/被拒绝。&#x27;</span>)</span><br><span class="line"></span><br><span class="line">    self.order = <span class="literal">None</span></span><br></pre></td></tr></table></figure>
<p>再把整个数据准备，建立回测对象的过程封装到类里吧。<br>放到一个新的文件backtest.py里。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># 量化交易回测类</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> backtrader <span class="keyword">as</span> bt</span><br><span class="line"><span class="keyword">import</span> backtrader.analyzers <span class="keyword">as</span> btay</span><br><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line"><span class="keyword">import</span> os</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 回测类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BackTest</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, strategy, start, end, code, name</span>):</span></span><br><span class="line">        self.__cerebro = <span class="literal">None</span></span><br><span class="line">        self.__strategy = strategy</span><br><span class="line">        self.__start = start</span><br><span class="line">        self.__end = end</span><br><span class="line">        self.__code = code</span><br><span class="line">        self.__name = name</span><br><span class="line">        self.__result = <span class="literal">None</span></span><br><span class="line">        self.__commission = <span class="number">0.0003</span></span><br><span class="line">        self.__initcash = <span class="number">0.01</span></span><br><span class="line">        self.init()</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 真正进行初始化的地方</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">init</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__cerebro = bt.Cerebro()</span><br><span class="line">        self.__cerebro.addstrategy(self.__strategy)</span><br><span class="line">        self.settingCerebro()</span><br><span class="line">        self.createDataFeeds()</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 设置cerebro</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">settingCerebro</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 添加回撤观察器</span></span><br><span class="line">        self.__cerebro.addobserver(bt.observers.DrawDown)</span><br><span class="line">        <span class="comment"># 设置手续费</span></span><br><span class="line">        self.__cerebro.broker.setcommission(commission=self.__commission)</span><br><span class="line">        <span class="comment"># 设置初始资金为0.01</span></span><br><span class="line">        self.__cerebro.broker.setcash(self.__initcash)</span><br><span class="line">        <span class="comment"># 添加分析对象</span></span><br><span class="line">        self.__cerebro.addanalyzer(btay.SharpeRatio, _name = <span class="string">&quot;sharpe&quot;</span>, riskfreerate = <span class="number">0.02</span>)</span><br><span class="line">        self.__cerebro.addanalyzer(btay.AnnualReturn, _name = <span class="string">&quot;AR&quot;</span>)</span><br><span class="line">        self.__cerebro.addanalyzer(btay.DrawDown, _name = <span class="string">&quot;DD&quot;</span>)</span><br><span class="line">        self.__cerebro.addanalyzer(btay.Returns, _name = <span class="string">&quot;RE&quot;</span>)</span><br><span class="line">        self.__cerebro.addanalyzer(btay.TradeAnalyzer, _name = <span class="string">&quot;TA&quot;</span>)</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 建立数据源</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">createDataFeeds</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(self.__code)):</span><br><span class="line">            df_data = self._getData(self.__code[i])</span><br><span class="line">            start_date = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, self.__start.split(<span class="string">&quot;-&quot;</span>)))</span><br><span class="line">            end_date = <span class="built_in">list</span>(<span class="built_in">map</span>(<span class="built_in">int</span>, self.__end.split(<span class="string">&quot;-&quot;</span>)))</span><br><span class="line">            dataFeed = bt.feeds.PandasData(dataname = df_data, name = self.__name[i], fromdate = datetime.datetime(start_date[<span class="number">0</span>], start_date[<span class="number">1</span>], start_date[<span class="number">2</span>]), todate = datetime.datetime(end_date[<span class="number">0</span>], end_date[<span class="number">1</span>], end_date[<span class="number">2</span>]))</span><br><span class="line">            self.__cerebro.adddata(dataFeed, name = self.__name[i])</span><br><span class="line">           </span><br><span class="line">    <span class="comment"># 获取账户总价值</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">getValue</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.__cerebro.broker.getvalue()</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 执行回测</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span>(<span class="params">self</span>):</span></span><br><span class="line">        print(<span class="string">&quot;初始资金:%.2f&quot;</span> % self.getValue())</span><br><span class="line">        self.__results = self.__cerebro.run()</span><br><span class="line">        print(<span class="string">&quot;期末资金:%.2f&quot;</span> % self.getValue())</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 输出回测结果</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">output</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__cerebro.plot(numfigs = <span class="number">2</span>)</span><br><span class="line">        plt.savefig(<span class="string">&quot;result.png&quot;</span>)</span><br><span class="line">        print(<span class="string">&quot;夏普比例:&quot;</span>, self.__results[<span class="number">0</span>].analyzers.sharpe.get_analysis()[<span class="string">&quot;sharperatio&quot;</span>])</span><br><span class="line">        print(<span class="string">&quot;年化收益率:&quot;</span>, self.__results[<span class="number">0</span>].analyzers.AR.get_analysis())</span><br><span class="line">        print(<span class="string">&quot;最大回撤:%.2f，最大回撤周期%d&quot;</span> % (self.__results[<span class="number">0</span>].analyzers.DD.get_analysis().<span class="built_in">max</span>.drawdown, self.__results[<span class="number">0</span>].analyzers.DD.get_analysis().<span class="built_in">max</span>.<span class="built_in">len</span>))</span><br><span class="line">        print(<span class="string">&quot;总收益率:%.2f&quot;</span> % (self.__results[<span class="number">0</span>].analyzers.RE.get_analysis()[<span class="string">&quot;rtot&quot;</span>]))</span><br><span class="line">        self.__results[<span class="number">0</span>].analyzers.TA.print()</span><br><span class="line">           </span><br><span class="line">    <span class="comment"># 获取数据</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_getData</span>(<span class="params">self, code</span>):</span></span><br><span class="line">        filename = code+<span class="string">&quot;.csv&quot;</span></span><br><span class="line">        print(<span class="string">&quot;./&quot;</span> + filename)</span><br><span class="line">        <span class="comment"># 已有数据文件，直接读取数据</span></span><br><span class="line">        <span class="keyword">if</span> os.path.exists(<span class="string">&quot;./&quot;</span> + filename):</span><br><span class="line">            df = pd.read_csv(filename)</span><br><span class="line">        <span class="keyword">else</span>: <span class="comment"># 没有数据文件，用tushare下载</span></span><br><span class="line">            df = ts.get_k_data(code, autype = <span class="string">&quot;qfq&quot;</span>, start = start,  end = end)</span><br><span class="line">            df.to_csv(filename)</span><br><span class="line">        df.index = pd.to_datetime(df.date)</span><br><span class="line">        df[<span class="string">&#x27;openinterest&#x27;</span>]=<span class="number">0</span></span><br><span class="line">        df=df[[<span class="string">&#x27;open&#x27;</span>,<span class="string">&#x27;high&#x27;</span>,<span class="string">&#x27;low&#x27;</span>,<span class="string">&#x27;close&#x27;</span>,<span class="string">&#x27;volume&#x27;</span>,<span class="string">&#x27;openinterest&#x27;</span>]]</span><br><span class="line">        <span class="keyword">return</span> df</span><br></pre></td></tr></table></figure>
<p>再调用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    <span class="comment"># 加载数据，建立数据源</span></span><br><span class="line">    start = <span class="string">&quot;2018-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2020-07-05&quot;</span></span><br><span class="line">    name = [<span class="string">&quot;300ETF&quot;</span>, <span class="string">&quot;nasETF&quot;</span>]</span><br><span class="line">    code = [<span class="string">&quot;510300&quot;</span>, <span class="string">&quot;513100&quot;</span>]</span><br><span class="line">    backtest = backtest.BackTest(TradeStrategy, start, end, code, name)</span><br><span class="line">    backtest.run()</span><br><span class="line">    backtest.output()</span><br></pre></td></tr></table></figure>
<p>跟重构以前的运行结果一致。merge到主分支上，删除refactoring分支，提交。<br>本文代码： <a target="_blank" rel="noopener" href="https://github.com/zwdnet/MyQuant/tree/master/46">https://github.com/zwdnet/MyQuant/tree/master/46</a> trade.py和backtest.py两个文件。<br>总结一下，重构主要目的是在不改变程序功能的前提下消除代码的“坏味道”，让代码更加可读，bug更少。我也尝试了一下用pytest进行测试驱动开发，感觉完全先写测试再写代码还是比较困难。尤其是一些读取数据，文件操作等地方，测试很难写。还是先写出个能干活的程序，再用重构的原则，一点一点改，改一点就运行吧。接下来打算用这些代码实现一些经典的交易策略吧。</p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/Backtrader/" rel="tag"># Backtrader</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/15/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B076%E2%80%94%E2%80%94CFA%E4%B8%80%E7%BA%A7%E7%AC%94%E8%AE%B004-%E7%BB%8F%E6%B5%8E%E5%AD%A6%E7%AC%AC%E4%B8%89%E9%83%A8%E5%88%86-Economics/" rel="next" title="量化投资学习笔记76——CFA一级笔记04:经济学第三部分(Economics)">
                <i class="fa fa-chevron-left"></i> 量化投资学习笔记76——CFA一级笔记04:经济学第三部分(Economics)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/07/18/%E7%89%99%E9%AB%93%E6%B2%BB%E7%96%97%E5%90%8E%E7%9A%84%E9%87%8D%E5%BA%A6%E7%A3%A8%E8%80%97%E7%89%99%E5%90%88%E8%B4%B4%E9%9D%A2%E4%BF%AE%E5%A4%8D/" rel="prev" title="牙髓治疗后的重度磨耗牙合贴面修复">
                牙髓治疗后的重度磨耗牙合贴面修复 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
